package io.gitee.sfch.chunmi.code.generator.service.impl;


import io.gitee.sfch.chunmi.code.generator.service.TableMetaService;
import io.gitee.sfch.chunmi.code.generator.service.TableMetaServiceManager;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 春米表源数据服务管理器
 */
@Service
public class TableMetaServiceManagerImpl implements TableMetaServiceManager {

    /**
     * 以数据库驱动类名进行映射的{@link TableMetaService}
     */
    private final Map<String, TableMetaService> tableMetaServiceMap = new HashMap<>();

    /**
     * 初始化{@link TableMetaServiceManagerImpl}，将所有扫描到的实现类按驱动类名进行映射
     *
     * @param tableMetaServices {@link TableMetaService}实现子类集合
     */
    public TableMetaServiceManagerImpl(List<TableMetaService> tableMetaServices) {
        for (TableMetaService tableMetaService : tableMetaServices) {
            String[] supportDriverNames = tableMetaService.supportDriverNames();
            if (supportDriverNames == null || supportDriverNames.length == 0) {
                throw new IllegalStateException("supportDriverNames is null or empty ->" + tableMetaService.getClass());
            }
            for (String supportDriverName : supportDriverNames) {
                tableMetaServiceMap.put(supportDriverName, tableMetaService);
            }
        }
    }

    @Override
    public TableMetaService getTableMetaService(String driverClassName) {
        TableMetaService tableMetaService = tableMetaServiceMap.get(driverClassName);
        if (tableMetaService == null) {
            throw new UnsupportedOperationException("未支持的数据库类型：" + driverClassName);
        }
        return tableMetaService;
    }

    @Override
    public void registerTableMetaService(String driverClassName, TableMetaService tableMetaService) {
        tableMetaServiceMap.put(driverClassName, tableMetaService);
    }
}
